package cn.chinaunicom.sdsi.upfc_demp.uploadtest.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.chinaunicom.sdsi.frm.base.BaseController;
import cn.chinaunicom.sdsi.frm.base.util.ResponseUtils;
import cn.chinaunicom.sdsi.upfc_demp.sys.entity.SysDemo;
import cn.chinaunicom.sdsi.upfc_demp.sys.service.SysDemoService;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("fileUploadController")
public class FileUploadController extends BaseController {

    @Autowired
    private Validator validator;

    private final Log log = LogFactory.getLog(FileUploadController.class);

    @Autowired
    private SysDemoService sysDemoService;

   /* @RequestMapping("/demoMain")
    public String goDemoMain() {
        return "frm/sys/sysDemoController/demoMain";
    }

    *//**
     * 跳转至导航式表单 样例
     * 
     * @return
     *//*
    @RequestMapping("/goNavFormDemo")
    public String goNavFormDemo() {
        return "frm/sys/sysDemoController/navFormDemo";
    }

    @RequestMapping("/hibrenateValidator")
    public String hibrenateValidator() {
        return "frm/sys/sysDemoController/hibrenateValidator";
    }

    @ResponseBody
    @RequestMapping("/saveValidatorSysDemo")
    public void saveValidatorSysDemo(@Valid SysDemo sysDemo, BindingResult result) {
        Set<ConstraintViolation<SysDemo>> ddd = validator.validate(sysDemo);
        System.out.println(ddd);
        System.out.println(sysDemo);
    }

    @RequestMapping("/ajaxJsp4Page")
    public String ajaxJsp4Page() {
        return "frm/sys/sysDemoController/ajaxJsp4Page";
    }

     @RequiresPermissions(value="",logical=Logical.OR) 
    @RequestMapping("/goDemo")
    public String goDemo() {
        log.info("跳转到上传下载示例页面！");
        return "frm/sys/sysDemoController/demo";
    }*/
    //jingrongze新增文件上传测试页面20170509
    @RequestMapping("/fileUpload")
    public String fileUpload() {
        log.info("跳转到上传文件测试页面！");
        return "frm/uploadtest/fileUploadController/fileUpload";
    }
    
    
/*
    @RequestMapping("/goDemos")
    public String goDemos() {
        log.info("跳转到excel示例页面!");
        return "frm/sys/sysDemoController/demos";
    }

    @RequestMapping("/goCharts")
    public String goCharts() {
        log.info("跳转到Charts示例页面!");
        return "frm/sys/sysDemoController/charts";
    }

    @RequestMapping("/goPages")
    public String goPages() {
        log.info("跳转到PageHelper示例页面!");
        return "frm/sys/sysDemoController/pages";
    }

    @RequestMapping("/searchDemo4Page")
    public String searchDemo4Page(Model model, SysDemo sd, Integer start, Integer pageSize) {
        model.addAttribute("pageInfo", sysDemoService.searchDemo4Page(sd, start, pageSize));
        // model.addAttribute("num",1/0);
        return "frm/sys/sysDemoController/pages";
    }

    @RequestMapping("/goDatas")
    public String goData() {
        log.info("跳转到DataTable示例页面！");
        return "frm/sys/sysDemoController/datas";
    }

    @ResponseBody
    @RequestMapping("/searchData4Page")
    public JSONObject searchData4Page(SysDemo sds, Integer start, Integer length) {
        return sysDemoService.searchData4Page(sds, start, length);
    }

    @RequestMapping("/goSubmit")
    public String goSubmit() {
        log.info("跳转到提交实体类示例页面");
        return "frm/sys/sysDemoController/submit";
    }

    @ResponseBody
    @RequestMapping(value = "/mutiEntity")
    public Map<String, String> mutiEntity(@RequestBody SysDemo[] demos) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("length", demos.length + "");
        StringBuilder builder = new StringBuilder(300);
        if (demos != null){
            for (int i = 0; i < demos.length; i++) {
                builder.append(demos[i].toString());
            }
        }
        map.put("content", builder.toString());
        return map;
    }

    @RequestMapping("/goForm")
    public String goFrom() {
        log.info("跳转到提交Form表单的页面");
        return "frm/sys/sysDemoController/form";
    }

    @ResponseBody
    @RequestMapping("/mutiForm")
    public SysDemo[] mutiForm(@RequestBody SysDemo[] demos) {
        return demos;
    }

    // 上传图片
    @ResponseBody
    @RequestMapping("/uploadPhoto")
    public String uploadPhoto(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        try {
            if (files != null) {
                for (MultipartFile file : files) {
                    InputStream in = file.getInputStream();
                    String filePath = request.getSession().getServletContext().getRealPath(".") + File.separatorChar + "photo";
                    String fileName = filePath + File.separatorChar + file.getOriginalFilename();
                    File path = new File(filePath);
                    File ofile = new File(fileName);
                    System.out.println(ofile.getAbsolutePath());
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    if (!ofile.exists()) {
                        ofile.createNewFile();
                    }
                    OutputStream out = new FileOutputStream(ofile);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    // 下载图片
    @RequestMapping("/downloadPhoto")
    public void downloadPhoto(HttpServletRequest request, HttpServletResponse response) {
        int width = 60; // 验证码图片的宽度
        int height = 20; // 验证码图片的高度
        int charCount = 4; // 验证码字符个数
        try {
            String fileName = ResponseUtils.responseFileName("图片下载示例.jpg", request.getHeader("USER-AGENT"));
            response.setContentType("application/x-msddownload;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);

            String validateCode = RandomStringUtils.randomNumeric(charCount);
            request.getSession().setAttribute("validateCode", validateCode);
            Random random = new Random();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.setColor(getRandColor(200, 250, random));// 设定图像背景色(因为是做背景，所以偏淡)
            g.fillRect(0, 0, width, height);// 填充图片区域

            // 产生随机干扰线，使图象中的验证码不易被其它程序探测到
            g.setColor(getRandColor(160, 200, random));
            
             * for(int i=0;i<50;i++){ int x1=random.nextInt(width); int y1=random.nextInt(height); int
             * x2=random.nextInt(12); int y2=random.nextInt(12); g.drawLine(x1,y1,x1+x2,y1+y2); }
             

            for (int i = 0; i < 100; i++) {
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                g.drawOval(x, y, 1, 1);
            }

            g.setColor(getRandColor(10, 150, random));// 生成随机颜色(因为是做前景，所以偏深)
            g.setFont(new Font("Times New Roman", Font.PLAIN, 22));// 设置字体
            g.drawString(validateCode, 6, height - 2);// 将验证码画到图片上
            g.dispose();// 图象生效

            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "JPEG", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }*/

    // 上传文件
    @ResponseBody
    @RequestMapping("/fileUploadTest")
    public String uploadExcel(@RequestParam("uploadFile") MultipartFile[] files, HttpServletRequest request) {
        try {
            if (files != null) {
                for (MultipartFile file : files) {
                    InputStream in = file.getInputStream();
                    String filePath = request.getSession().getServletContext().getRealPath(".") + File.separatorChar + "uploadFile";
                    String fileName = filePath + File.separatorChar + file.getOriginalFilename();
                    File path = new File(filePath);
                    File ofile = new File(fileName);
                    System.out.println(ofile.getAbsolutePath());
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    if (!ofile.exists()) {
                        ofile.createNewFile();
                    }
                    OutputStream out = new FileOutputStream(ofile);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                    //将文件数据放到数据库中
                    
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    // 下载文件
    /*@RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileName = ResponseUtils.responseFileName("世界和平.xlsx", request.getHeader("USER-AGENT"));
            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);

            OutputStream out = response.getOutputStream();
            SXSSFWorkbook wb = new SXSSFWorkbook(100);
            // keep 100 rows in memory, exceeding rows will be flushed to disk
            Sheet sh = wb.createSheet();
            for (int rownum = 0; rownum < 1000; rownum++) {
                Row row = sh.createRow(rownum);
                for (int cellnum = 0; cellnum < 10; cellnum++) {
                    Cell cell = row.createCell(cellnum);
                    String address = new CellReference(cell).formatAsString();
                    cell.setCellValue(address + "号");
                }
            }
            wb.write(out);
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Color getRandColor(int fc, int bc, Random random) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int minus = bc - fc;
        int r = fc + random.nextInt(minus);
        int g = fc + random.nextInt(minus);
        int b = fc + random.nextInt(minus);
        return new Color(r, g, b);
    }

    *//**
     * @Description:获取echarts图所需数据
     * @return Map<String,Object> 封装了echarts图表数据的map legend：数据分组 category：横坐标 series：要展示的数据
     * @author: 马媛媛
     * @time:2017年2月20日 下午4:15:04
     *//*
    @ResponseBody
    @RequestMapping("/getChartData")
    public Map<String, Object> getChartData() {
        List<String> legend = new ArrayList<String>();// 数据分组
        List<List<String>> category = new ArrayList<List<String>>();// 横坐标
        List<Map<String, Object>> series = new ArrayList<Map<String, Object>>();// 要展示的数据 ， 数据分组中有几个值，series中包含几个serie
        Map<String, Object> map = new HashMap<String, Object>();// 封装返回的数据

        legend.add("上海");
        legend.add("北京");
        legend.add("济南");

        List<String> category1 = new ArrayList<String>();// 横坐标的值
        category1.add("20");
        category1.add("22");
        category1.add("26");
        category1.add("29");
        category1.add("30");
        category1.add("31");
        category1.add("39");
        category.add(category1);

        // List<String> category2 = new ArrayList<String>();//横坐标的值
        // category2.add("155");
        // category2.add("160");
        // category2.add("165");
        // category2.add("170");
        // category2.add("175");
        // category2.add("180");
        // category2.add("185");
        // category.add(category2);

        Map<String, Object> serie1 = new HashMap<String, Object>();// 与数据分组的内容对应，
        List<Integer> seriesData1 = new ArrayList<Integer>();//
        seriesData1.add(120);
        seriesData1.add(132);
        seriesData1.add(101);
        seriesData1.add(134);
        seriesData1.add(90);
        seriesData1.add(230);
        seriesData1.add(210);
        serie1.put("data", seriesData1);

        // 饼形图数据
        Map<String, Object> seriesData = new HashMap<String, Object>();
        seriesData.put("上海", 335);
        seriesData.put("北京", 310);
        seriesData.put("济南", 234);
        serie1.put("dataPie", seriesData);
        series.add(serie1);

        Map<String, Object> serie2 = new HashMap<String, Object>();// 与数据分组的内容对应，数据分组中有几个值，series中包含几个serie
        List<Integer> seriesData2 = new ArrayList<Integer>();//
        seriesData2.add(220);
        seriesData2.add(182);
        seriesData2.add(191);
        seriesData2.add(234);
        seriesData2.add(90);
        seriesData2.add(290);
        seriesData2.add(310);
        serie2.put("data", seriesData2);
        series.add(serie2);

        Map<String, Object> serie3 = new HashMap<String, Object>();// 与数据分组的内容对应，数据分组中有几个值，series中包含几个serie
        List<Integer> seriesData3 = new ArrayList<Integer>();//
        seriesData3.add(150);
        seriesData3.add(232);
        seriesData3.add(201);
        seriesData3.add(154);
        seriesData3.add(190);
        seriesData3.add(330);
        seriesData3.add(410);
        serie3.put("data", seriesData3);
        series.add(serie3);

        map.put("legend", legend);
        map.put("category", category);
        map.put("series", series);
        return map;
    }*/

}
